package pers.cz.transform;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.LoaderClassPath;

import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

/**
 * @program: PostGirl-panent
 * @description: 实时日志转发
 * @author: Cheng Zhi
 * @create: 2022-07-01 14:14
 **/
public class LogForwardTransformer implements ITransformer{

    public final String TEST_CLASS_NAME = "org.apache.logging.slf4j.Log4jLogger";

    public final String[] METHOD_NAMES = new String[] {"info,debug,error,trace,warn"};

    @Override
    public void doInert(String... params) {

    }

    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {

        String finalClassName = className.replace("/", ".");
        if (finalClassName.equals(TEST_CLASS_NAME)) {
            // 动态修改代码
            try {
                ClassPool classPool = new ClassPool(true);
                classPool.insertClassPath(new LoaderClassPath(loader));
                // 获取目标类
                CtClass ctClass = classPool.get(TEST_CLASS_NAME);
                for (int i=0; i< METHOD_NAMES.length; i++) {
                    // 获取要监听的方法
                    CtMethod beginMethod = ctClass.getDeclaredMethod(METHOD_NAMES[i]);
                    String src =
                            "{" +
                                    "pers.cz.netty.Client.sendMsg($1);" +
                                    "}";
                    beginMethod.insertAfter(src);
                }

                //beginMethod.insertAt(68, src);
                // 加载到jvm
                return ctClass.toBytecode();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
